import json
import os
import re
import subprocess
import time
from pprint import pprint

from tqdm import tqdm
import requests
from lxml import etree

print("所有视频将保存在  D:\B站视频")
if not os.path.exists('D:\B站视频'):
    os.mkdir('D:\B站视频')

while True:
    url = input("请粘贴视频播放链接：")
    # time.sleep(1)
    # print("正在下载，请稍后......")
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.0.0 Safari/537.36',
        'Referer': 'https://www.bilibili.com/'
    }
    response = requests.get(url=url, headers=headers)
    info = re.findall('window.__playinfo__=(.*?)</script>', response.text)[0]
    pprint(info)
    # video_url = json.loads(info)["data"]["dash"]["video"][0]["baseUrl"]
    # audio_url = json.loads(info)["data"]["dash"]["audio"][0]["baseUrl"]
    # html = etree.HTML(response.text)
    # filename = html.xpath('//*[@id="viewbox_report"]/h1/text()')[0]
    # filename = re.sub('[\\\/|":*? ]', '-', filename)
    # name = filename + '(合成)'
    #
    # # v_con = requests.get(url=video_url, headers=headers).content
    # # a_con = requests.get(url=audio_url, headers=headers).content
    #
    # video = requests.get(video_url, stream=True)
    # file_size = video.headers.get('Content-Length')
    # video_pbar = tqdm(total=file_size)
    # with open(f'D:\B站视频/{name}.mp4', mode='wb') as f:
    #     for video_chunk in video.iter_content(1024 * 1024):
    #         f.write(video_chunk)
    #         video_pbar.set_description(f'{name}---Downloading...')
    #         video_pbar.update(1024 * 1024)
    #     video_pbar.set_description('Done!!!')
    #     video_pbar.close()

    # 音频和视频合并
    # cmd = f'ffmpeg - i {filename}.mp4 -i {filename}.mp3 -c:v copy -c:a copy {name}.mp4'
    # os.system(cmd)
    # cmd = f'ffmpeg -i D:\B站视频/{filename}.mp4 -i D:\B站视频/{filename}.mp3 -c:v copy -c:a copy D:\B站视频/{name}.mp4'
    # subprocess.run(cmd, shell=True)
    # os.remove(f'D:\B站视频/{filename}.mp3')
    # os.remove(f'D:\B站视频/{filename}.mp4')
    # print("下载完成！！！")
